<template>
  <div class="add-admin-page">
    <!-- 顶部标题栏 -->
    <header class="header">
      <div class="logo">
        <el-button type="primary" @click="handleBack" style="font-size: 16px;font-weight: bold;">
          <el-icon style="font-size: 20px;">
            <Back />
          </el-icon>&nbsp;&nbsp;返回</el-button>
      </div>
      <h1>新增普通管理员</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 基本信息 -->
      <div class="info-header">
        <span>加入日期: {{ joinDate }}</span>
        <span>注销日期: N/A</span>
      </div>
      <div class="admin-form">

        <!-- 表单内容 -->
        <div class="form-content" v-loading="formLoading">
          <div class="form-row">
            <div class="form-item">
              <label>普通管理员账号：</label>
              <div class="input-wrapper">
                <el-input 
                  v-model="adminInfo.account" 
                  placeholder="请输入账号" 
                  :class="{ 'error': accountError }"
                  @input="validateAccount(adminInfo.account)"
                />
                <div class="error-message" v-if="accountError">{{ accountError }}</div>
              </div>
            </div>
            <div class="form-item">
              <label>普通管理员密码设置：</label>
              <div class="input-wrapper">
                <el-input 
                  v-model="adminInfo.password" 
                  type="password" 
                  show-password 
                  :class="{ 'error': passwordError }"
                  placeholder="请输入密码"
                  @input="validatePassword(adminInfo.password)"
                />
                <div class="error-message" v-if="passwordError">{{ passwordError }}</div>
              </div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label>控制人：</label>
              <div class="input-wrapper">
                <el-input v-model="adminInfo.controller" placeholder="请输入控制人姓名" />
              </div>
            </div>
            <div class="form-item">
              <label>重复密码：</label>
              <div class="input-wrapper">
                <el-input 
                  v-model="adminInfo.confirmPassword" 
                  type="password" 
                  show-password 
                  :class="{ 'error': confirmPasswordError }"
                  placeholder="请再次输入密码"
                  @input="validateConfirmPassword"
                />
                <div class="error-message" v-if="confirmPasswordError">{{ confirmPasswordError }}</div>
              </div>
            </div>
          </div>

          <!-- 权限设置 -->
          <div class="permissions-section">
            <div class="section-header">
              <label class="section-label">管理员权限设置：</label>
            </div>
            <div class="permissions-grid">
              <el-checkbox v-model="permissions.userManage" class="custom-checkbox">用户管理</el-checkbox>
              <el-checkbox v-model="permissions.meetingManage" class="custom-checkbox">会议管理</el-checkbox>
              <el-checkbox v-model="permissions.activityManage" class="custom-checkbox">活动管理</el-checkbox>
              <el-checkbox v-model="permissions.checkInManage" class="custom-checkbox">签到管理</el-checkbox>
              <el-checkbox v-model="permissions.newsPublish" class="custom-checkbox">新闻发布</el-checkbox>
              <el-checkbox v-model="permissions.homeEdit" class="custom-checkbox">主页编辑</el-checkbox>
            </div>

            <div class="special-permissions">
              <div class="permission-row">
                <el-checkbox v-model="permissions.proposalManage" class="custom-checkbox">提案管理</el-checkbox>
                <el-select v-model="adminInfo.proposalDepartment" placeholder="选择部门"
                  :disabled="!permissions.proposalManage" @change="handleProposalDepartmentChange">
                  <el-option v-for="dept in proposalDepartments" :key="dept.id" :label="dept.name" :value="dept.id" />
                </el-select>
              </div>

              <div class="permission-row">
                <el-checkbox v-model="permissions.socialInfoManage" class="custom-checkbox">社情民意管理</el-checkbox>
                <el-select v-model="adminInfo.socialDepartment" placeholder="选择部门"
                  :disabled="!permissions.socialInfoManage" @change="handleSocialDepartmentChange">
                  <el-option v-for="dept in socialDepartments" :key="dept.id" :label="dept.name" :value="dept.id" />
                </el-select>
              </div>
            </div>
          </div>
        </div>
      </div>
      
        <!-- 底部按钮 -->
        <div class="form-actions">
          <!-- <el-button @click="handleBack">返 回</el-button> -->
          <el-button type="primary" @click="handleSave">确定保存</el-button>
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addAdmin, checkAccountExists } from '@/api/super'
import { useDepartmentStore } from '@/stores/department'
import Time from '@/components/time.vue'
const router = useRouter()


// 获取当前日期作为加入日期
const joinDate = new Date().toLocaleDateString('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
}).replace(/\//g, '-')

// 管理员信息
const adminInfo = ref({
  account: '',
  password: '',
  controller: '',
  confirmPassword: '',
  proposalDepartment: '',
  socialDepartment: '',
  propositionsDepId: null,
  publicDepId: null
})

// 权限设置
const permissions = ref({
  userManage: false,
  meetingManage: false,
  activityManage: false,
  checkInManage: false,
  newsPublish: false,
  homeEdit: false,
  proposalManage: false,
  socialInfoManage: false
})

const departmentStore = useDepartmentStore()

// 改用 store 中的数据
const proposalDepartments = computed(() => departmentStore.proposalDepartments)
const socialDepartments = computed(() => departmentStore.socialDepartments)

// 处理提案部门选择变化
const handleProposalDepartmentChange = (deptId) => {
  adminInfo.value.propositionsDepId = deptId
}

// 处理社情民意部门选择变化
const handleSocialDepartmentChange = (deptId) => {
  adminInfo.value.publicDepId = deptId
}

// 返回上一页
const handleBack = () => {
  router.back()
}

const pageLoading = ref(false)
const formLoading = ref(false)

// 验证规则
const accountRules = {
  pattern: /^[a-zA-Z0-9]{5,16}$/,
  message: '账号必须是5-16位英文字母或数字'
}

const passwordRules = {
  pattern: /^[a-zA-Z0-9]{5,16}$/,
  message: '密码必须是5-16位英文字母或数字'
}

// 验证状态
const accountError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')

// 账号输入验证
const validateAccount = async (value) => {
  if (!value) {
    accountError.value = '请输入账号'
    return false
  }
  if (!accountRules.pattern.test(value)) {
    accountError.value = accountRules.message
    return false
  }
  
  try {
    const response = await checkAccountExists(value)
    if (response.data) {
      accountError.value = '该账号已存在'
      return false
    }
  } catch (error) {
    ElMessage.error('检查账号失败')
    return false
  }
  
  accountError.value = ''
  return true
}

// 密码输入验证
const validatePassword = (value) => {
  if (!value) {
    passwordError.value = '请输入密码'
    return false
  }
  if (!passwordRules.pattern.test(value)) {
    passwordError.value = passwordRules.message
    return false
  }
  passwordError.value = ''
  return true
}

// 确认密码验证
const validateConfirmPassword = () => {
  if (!adminInfo.value.confirmPassword) {
    confirmPasswordError.value = '请确认密码'
    return false
  }
  if (adminInfo.value.password !== adminInfo.value.confirmPassword) {
    confirmPasswordError.value = '两次输入的密码不一致'
    return false
  }
  confirmPasswordError.value = ''
  return true
}

// 修改保存方法
const handleSave = async () => {
  formLoading.value = true
  try {
    // 表单验证
    const isAccountValid = await validateAccount(adminInfo.value.account)
    const isPasswordValid = validatePassword(adminInfo.value.password)
    const isConfirmPasswordValid = validateConfirmPassword()

    if (!isAccountValid || !isPasswordValid || !isConfirmPasswordValid) {
      formLoading.value = false
      return
    }

    if (!adminInfo.value.controller) {
      ElMessage.error('请输入控制人姓名')
      return
    }

    if (permissions.value.proposalManage && !adminInfo.value.proposalDepartment) {
      ElMessage.error('请选择提案管理部门')
      return
    }
    if (permissions.value.socialInfoManage && !adminInfo.value.socialDepartment) {
      ElMessage.error('请选择社情民意管理部门')
      return
    }

    // 调用API保存管理员信息
    const response = await addAdmin({
      account: adminInfo.value.account,
      password: adminInfo.value.password,
      controller: adminInfo.value.controller,
      manageUsers: permissions.value.userManage,
      manageMeetings: permissions.value.meetingManage,
      manageEvents: permissions.value.activityManage,
      manageCheckIns: permissions.value.checkInManage,
      publishNews: permissions.value.newsPublish,
      editHomePage: permissions.value.homeEdit,
      managePropositions: permissions.value.proposalManage,
      managePublic: permissions.value.socialInfoManage,
      propositionsDepId: adminInfo.value.propositionsDepId,
      publicDepId: adminInfo.value.publicDepId
    });
    ElMessage.success('添加成功');
    router.back(); // 返回上一页
  } catch (error) {
    ElMessage.error('添加管理员失败');
  } finally {
    formLoading.value = false
  }
}



onMounted(async () => {
  pageLoading.value = true
  try {
    await departmentStore.fetchDepartments()
  } finally {
    pageLoading.value = false
  }
})

</script>

<style scoped>
@import '@/assets/css/header/index.css';
@import '@/assets/css/add.css';

.error-message {
  color: #F56C6C;
  font-size: 12px;
  margin-top: 0px;
  min-height: 18px;
  line-height: 1;
}

</style>